package com.etcn.manager.controller;


import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.etcn.manager.model.TUser;
import com.etcn.manager.model.UserOpenResourceserver;
import com.etcn.manager.service.DevOpenResManagerService;
import com.etcn.manager.service.UserManagerService;
/**
 * 
 * @author Mr Zhou
 *
 */
@Controller
@RequestMapping("/user")
public class UserManageController extends BaseController{
	@Inject
	private UserManagerService userManagerService;
	@Inject
	private DevOpenResManagerService devOpenResManagerService;
	//admin
	@RequestMapping("/getAllUsers")
	public String getAllUsers(ModelMap model,Integer pageNow,HttpServletRequest request,Integer query_userType) {
		String userType = getUserType(request);
		if(userType!=null && !"".equals(userType) && userType.equals(USERTYPE_ADMIN)){
			String uType="";
			if(query_userType ==null || query_userType==0) {
				query_userType = 0;
				uType = USERTYPE_ADMIN;
			}
			else if(query_userType==1) uType = USERTYPE_DEV;
			else return "error/error";
			if(pageNow==null||pageNow<1)pageNow=1;
			Pageable pageable = new  PageRequest(pageNow-1,5,new Sort(Direction.DESC,"id"));
			Page<TUser> usersPage =userManagerService.getUsersPageable(uType,pageable);
			List<TUser> userList = usersPage.getContent();
			
			model.addAttribute("userList",userList);
			model.addAttribute("totalPage",usersPage.getTotalPages());
			model.addAttribute("totalNum",usersPage.getTotalElements());
			model.addAttribute("pageNow",pageNow);
			model.addAttribute("userType",query_userType);
			return "userlist";
		}else{
			return "error/authoritymsg";
		}
	}
	
	//admin
		@RequestMapping("/getAllUsersForPop")
		public String getAllUsersForPop(ModelMap model,Integer pageNow,HttpServletRequest request,Integer query_userType,Long resServerId) {
			String userType = getUserType(request);
			if(userType!=null && !"".equals(userType) && userType.equals(USERTYPE_ADMIN)){
				String uType="";
				if(query_userType ==null || query_userType==0) {
					query_userType = 0;
					uType = USERTYPE_ADMIN;
				}
				else if(query_userType==1) uType = USERTYPE_DEV;
				else return "error/error";
				if(pageNow==null||pageNow<1)pageNow=1;
				Pageable pageable = new  PageRequest(pageNow-1,5,new Sort(Direction.DESC,"id"));
				Page<TUser> usersPage =userManagerService.getUsersPageable(uType,pageable);
				List<TUser> userList = usersPage.getContent();
				List<UserOpenResourceserver> uorList = devOpenResManagerService.getByUserIdListAndResourceServerId(userList, resServerId);
				Map<Integer,Date> uorMap = new HashMap<Integer,Date>();
				for(UserOpenResourceserver uor:uorList){
					uorMap.put(uor.getId().getUserId(), uor.getEndDate());
				}
				model.addAttribute("userList",userList);
				model.addAttribute("totalPage",usersPage.getTotalPages());
				model.addAttribute("totalNum",usersPage.getTotalElements());
				model.addAttribute("pageNow",pageNow);
				model.addAttribute("userType",query_userType);
				model.addAttribute("uorMap",uorMap);
				model.addAttribute("date",new Date());
				return "devlist";
			}else{
				return "error/authoritymsg";
			}
		}
	
	//admin  dev
	@RequestMapping("/jumpMain")
	public String jumpMain(HttpServletRequest request){
		String userType = getUserType(request);
		if( USERTYPE_ADMIN.equals(userType)){
			return "main";
		}else if(USERTYPE_DEV.equals(userType)){
			return "developer/main";
		}
		else{
			return "error/authoritymsg";
		}
	}
	
	@RequestMapping("/jumpIndex")
	public String jumpIndex(HttpServletRequest request){
		String userType = getUserType(request);
		if( USERTYPE_ADMIN.equals(userType)){
			return "main";
		}else if(USERTYPE_DEV.equals(userType)){
			return "developer/index";
		}
		else{
			return "error/authoritymsg";
		}
	}
	
	//admin  dev
	@RequestMapping("/pwdUpdateJump")
	public String pwdUpdateJump(){
		return "pwdupdate";
	}
	
	
	//admin  dev
	@RequestMapping("/pwdUpdate")
	public String pwdUpdate(HttpServletRequest request, String newPassword,String oldPassword,String confirmPassword) throws IOException{
		String name1 = (String)request.getSession().getAttribute("dev_username");
		String name2 = (String)request.getSession().getAttribute("username");
		String name="";
		if(!"".equals(name1)&& name1!=null)  name=name1;
		if(!"".equals(name2)&& name2!=null)   name=name2;
		if(!"".equals(name)&& name!=null){
			TUser user =userManagerService.getUserByUserName(name);
			if(oldPassword!=null && oldPassword.equals(user.getPassword())&& !"".equals(newPassword)&&newPassword!=null && newPassword.equals(confirmPassword)){
				user.setPassword(newPassword);
				userManagerService.update(user);
				return "success";
			}
			return "error";
		}else{
			return "error/authoritymsg";
		}
	}
	
	//admin  dev
	@RequestMapping("/checkPwd")
	public @ResponseBody  String checkPwd(HttpServletRequest request, String oldPassword) throws IOException{
		String name1 = (String)request.getSession().getAttribute("dev_username");
		String name2 = (String)request.getSession().getAttribute("username");
		String name="";
		if(!"".equals(name1)&& name1!=null)  name=name1;
		if(!"".equals(name2)&& name2!=null)   name=name2;
		if(!"".equals(name)&& name!=null){
			TUser user =userManagerService.getUserByUserName(name);
			String rightPwd= user.getPassword();
			if(oldPassword!=null && oldPassword.equals(rightPwd)){
				return "1";
			}else{
				return "0";
			}
		}else{
			return "error/authoritymsg";
		}
	}
	//admin
	/**
	 * check admin user is valid or not
	 * @author Mr Zhou
	 * @param request
	 * @return
	 */
	@RequestMapping("/checkUser")
	public @ResponseBody boolean checkUser(HttpServletRequest request){
		String username = request.getParameter("j_username");
		String password = request.getParameter("j_password");
		TUser user =  userManagerService.checkUser(username, password);
		if(user!=null){
			request.getSession().setAttribute("username", username);
			request.getSession().setAttribute("userId", user.getId());
			request.getSession().setAttribute("userType", user.getUserType());
			return true;
		}
		return  false;
	}
	//dev
	/**
	 * check developer's account if is registered or not
	 * @param request
	 * @return
	 */
	@RequestMapping("/checkDevUser")
	public @ResponseBody boolean checkDevUser(HttpServletRequest request){
		String username = request.getParameter("j_username");
		String password = request.getParameter("j_password");
		TUser user =  userManagerService.checkDevUser(username, password);
		if(user!=null){
			request.getSession().setAttribute("dev_username", username);
			request.getSession().setAttribute("userId", user.getId());
			request.getSession().setAttribute("petName", user.getPetName());
			request.getSession().setAttribute("userType", user.getUserType());
			return  true;
		}
		return false;
	}
	//admin
	/*
	 * 后台添加用户跳转方法，需要权限验证
	 */
	@RequestMapping("/registeJump")
	public String registeJump(ModelMap model,HttpServletRequest request,Integer uType){
		String userType = getUserType(request);
		if(userType!=null && !"".equals(userType) && userType.equals(USERTYPE_ADMIN)){
			model.addAttribute("userType",uType);
			return "registe";
		}else{
			return "error/authoritymsg";
		}
	}
	//dev
	@RequestMapping("/devRegisteJump")
	public String devRegisteJump(){
		return "developer/registe2";
	}
	
	//admin dev
	@RequestMapping("/checkUsernameExist")
	public @ResponseBody boolean  checkUsername(HttpServletRequest request){
		String username = request.getParameter("username");
		boolean isvalid = userManagerService.checkUsernameExist(username);
		return  isvalid;
	}
	
	//admin
	/**
	 * backstage add user
	 * @param request
	 * @param user
	 * @return
	 */
	@RequestMapping("/addUser")
	public  String  addUser(HttpServletRequest request,TUser user){
		String username = user.getUsername();
		String password = user.getPassword();
		if("".equals(username)||username==null || "".equals(password)||password==null){
			return "error/error";
		}
		String userType = getUserType(request);
		if(userType!=null && !"".equals(userType) && userType.equals(USERTYPE_ADMIN)){
			user.setDelete(false);
			user.setPass(true);
			//user.setUserType("admin");
			boolean isvalid = userManagerService.save(user);
			if(isvalid){
				if(USERTYPE_ADMIN.equals(user.getUserType())) return  "redirect:getAllUsers?query_userType=0";
				else if(USERTYPE_DEV.equals(user.getUserType())) return "redirect:getAllUsers?query_userType=1";
				else return "error/error";
			}else{
				return "error/error";
			}
		}else{
			return "error/authoritymsg";
		}
	}
	
	
	//dev
	/**
	 * developer register
	 * @param request
	 * @param user
	 * @return
	 */
	@RequestMapping("/devRegiste")
	public  String  registerDev(HttpServletRequest request,TUser user){
			String username = user.getUsername();
			String password = user.getPassword();
			if("".equals(username)||username==null || "".equals(password)||password==null){
				return "error/error";
			}
			user.setUserType("developer");
			boolean isvalid = userManagerService.save(user);
			if(isvalid){
				return  "developer/reg_success";
			}else{
				return "error/error";
			}
	}
	
	
	@RequestMapping("/logout")
	public void logout(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException{
		HttpSession session = request.getSession();
		//session.removeAttribute("");
		session.invalidate();
		response.sendRedirect("../../oauth2/authorize?response_type=token&client_id=authorization-server-admin-js-client&scope=read,write&redirect_uri=http://localhost:8080/apis-oauth2-server/client/client.html");
	}
}
